package com.imay.live.proto.helper;

import android.content.Context;
import android.os.Build;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.imay.base.util.MD5Util;
import com.imay.base.util.NetworkUtil;
import com.imay.live.Constants;
import com.imay.live.IMApplication;
import com.imay.live.helper.UmengPushHelper;
import com.imay.live.proto.ReportType;
import com.imay.live.proto.RptReportReq;
import com.imay.live.proto.account.AccountAuthSessionReq;
import com.imay.live.proto.account.AccountCreateReq;
import com.imay.live.proto.MessageId;
import com.imay.live.proto.UserDeviceInfo;
import com.imay.live.proto.account.AccountLogoutReq;
import com.imay.live.proto.account.AccountReportDelayReq;
import com.imay.live.proto.room.RoomChatReq;
import com.imay.live.proto.room.RoomCheckAdminReq;
import com.imay.live.proto.room.RoomCommonReq;
import com.imay.live.proto.room.RoomKickUserReq;
import com.imay.live.proto.room.RoomLikeReq;
import com.imay.live.proto.room.RoomLinkConfirmReq;
import com.imay.live.proto.room.RoomLinkInviteReq;
import com.imay.live.proto.room.RoomListUserReq;
import com.imay.live.proto.room.RoomSetAdminReq;
import com.imay.live.proto.room.RoomSetCityReq;
import com.imay.live.proto.room.RoomSetLiveFaceReq;
import com.imay.live.proto.room.RoomSetLiveStatusReq;
import com.imay.live.proto.room.RoomSilenceUserReq;
import com.imay.live.proto.room.RoomStartLiveReq;
import com.imay.live.proto.sns.SnsFollowUserReq;
import com.imay.live.proto.user.UserInfoCardReq;
import com.imay.live.BuildConfig;

import java.util.List;

/**
 * Created by jeaman on 2017/3/30.
 */

public class ProtoSocketFactory extends ProtoFactory {
    private static final String PROTO_VERSION = "7.7.7";
    private static final long DEFAULT_TIMEOUT = 30000;  //SOCKET 默认超时

    //生成socket请求的json字符串
    private static ProtoRequestParams generateSocketParams(int messageId, Object object) {
        int seqId = generateSeqId();
        String command = COMMAND_PREFIX_SOCKET + seqId;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("msg_id", messageId);
        jsonObject.put("seq", seqId);
        jsonObject.put("timeout", DEFAULT_TIMEOUT);
        jsonObject.put("content", JSON.toJSON(object));
        return new ProtoRequestParams(REQUEST_TYPE_SOCKET, command, jsonObject.toJSONString());
    }


    public static UserDeviceInfo getUserDeviceInfo() {
        TelephonyManager tm = (TelephonyManager) IMApplication.getInstance().getSystemService(Context.TELEPHONY_SERVICE);
        UserDeviceInfo userDeviceInfo = new UserDeviceInfo();
        try {
            userDeviceInfo.DeviceImei = tm.getDeviceId();
        } catch (Exception e) {
            userDeviceInfo.DeviceImei = "0000000000000";
        }
        userDeviceInfo.Isp = tm.getSimOperator();
        userDeviceInfo.DevicePhoneModel = Build.MODEL;
        userDeviceInfo.DeviceOs = "android";
        userDeviceInfo.DeviceOsVersion = Build.VERSION.RELEASE;
        userDeviceInfo.DeviceMac = NetworkUtil.getMacAddress(IMApplication.getInstance());
//        userDeviceInfo.Ip = NetworkUtil.getLocalIp(IMApplication.getInstance());
        userDeviceInfo.Network = NetworkUtil.getNetworkType(IMApplication.getInstance());
        userDeviceInfo.Version = BuildConfig.VERSION_NAME;
//        userDeviceInfo.Uuid = AppUtil.generateDeviceId(IMApplication.getInstance());

//        userDeviceInfo.ResourceVersion = "2017.0123.2776";
//        userDeviceInfo.City = "广东,广州";
//        userDeviceInfo.Longitude = 113320892;
//        userDeviceInfo.Latitude = 23107484;
        userDeviceInfo.DeviceToken = UmengPushHelper.getInstance().getDeviceToken();
        userDeviceInfo.Channel = Constants.sChannelName;

        return userDeviceInfo;
    }

    // (TCP)发送AccountAuthSessionReq
    public static ProtoRequestParams requestAuthSession(long uid, String accessToken) {
        long timestamp = System.currentTimeMillis() / 1000L;
        String signature = MD5Util.getSHA1(uid + "" + timestamp + "" + accessToken);
        if (!TextUtils.isEmpty(signature)) {
            signature = signature.substring(0, 12);
        }
        AccountAuthSessionReq request = new AccountAuthSessionReq();
        request.uid = uid;
        request.timestamp = timestamp;
        request.signature = signature;
        request.device = getUserDeviceInfo();
        request.userRoomBatchNotify = true;
        return generateSocketParams(MessageId.accountAuthSessionReq, request);
    }

    //TCP连接的第二个消息(主要发送友盟推送token)
    public static ProtoRequestParams requestAccountReportDelay() {
        AccountReportDelayReq request = new AccountReportDelayReq();
        request.device = getUserDeviceInfo();
        return generateSocketParams(MessageId.accountReportDelayReq, request);
    }

    //登录房间
    public static ProtoRequestParams requestJoinRoom(long roomId) {
        RoomCommonReq request = new RoomCommonReq();
        request.roomId = roomId;
        return generateSocketParams(MessageId.roomEnterReq, request);
    }

    //离开房间
    public static ProtoRequestParams requestLeaveRoom(long roomId) {
        RoomCommonReq request = new RoomCommonReq();
        request.roomId = roomId;
        return generateSocketParams(MessageId.roomLeaveReq, request);
    }

    //获取开播信息
    public static ProtoRequestParams requestMyLiveInfo() {
        return generateSocketParams(MessageId.roomGetMyLiveInfoReq, null);
    }

    //开始直播
    public static ProtoRequestParams requestStartLive(String title, String coverUrl, String city, double latitude, double longitude, List<String> tags) {
        RoomStartLiveReq request = new RoomStartLiveReq();
        request.title = title;
        request.imgFace = coverUrl;
        request.city = city;
        //经纬度乘以1百万转为整型
        if (latitude > 0) {
            request.latitude = (long) (latitude * 1000000);
        }
        if (longitude > 0) {
            request.longitude = (long) (longitude * 1000000);
        }
        request.labels = tags;
        return generateSocketParams(MessageId.roomStartLiveReq, request);
    }

    //设置城市
    public static ProtoRequestParams requestSetCity(String city, double latitude, double longitude) {
        RoomSetCityReq request = new RoomSetCityReq();
        request.city = city;
        //经纬度乘以1百万转为整型
        if (latitude > 0) {
            request.latitude = (long) (latitude * 1000000);
        }
        if (longitude > 0) {
            request.longitude = (long) (longitude * 1000000);
        }
        return generateSocketParams(MessageId.roomSetCityReq, request);
    }

    //设置封面
    public static ProtoRequestParams requestSetCover(String coverUrl) {
        RoomSetLiveFaceReq request = new RoomSetLiveFaceReq();
        request.imgFace = coverUrl;
        return generateSocketParams(MessageId.roomSetLiveFaceReq, request);
    }

    //结束直播
    public static ProtoRequestParams requestEndLive() {
        return generateSocketParams(MessageId.roomEndLiveReq, null);
    }

    //直播状态
    public static ProtoRequestParams requestSetLivePause() {
        return requestSetLiveStatus(RoomSetLiveStatusReq.LIVE_PAUSE);
    }

    public static ProtoRequestParams requestSetLiveResume() {
        return requestSetLiveStatus(RoomSetLiveStatusReq.LIVE_RESUME);
    }

    public static ProtoRequestParams requestSetLiveReconnect() {
        return requestSetLiveStatus(RoomSetLiveStatusReq.LIVE_RECONNECT);
    }

    public static ProtoRequestParams requestSetLiveBusy() {
        return requestSetLiveStatus(RoomSetLiveStatusReq.LIVE_BUSY);
    }

    private static ProtoRequestParams requestSetLiveStatus(int status) {
        RoomSetLiveStatusReq request = new RoomSetLiveStatusReq();
        request.status = status;
        return generateSocketParams(MessageId.roomSetLiveStatusReq, request);
    }

    //房间聊天
    public static ProtoRequestParams requestRoomChat(long roomId, long atUid, String content) {
        RoomChatReq request = new RoomChatReq();
        request.roomId = roomId;
        request.content = content;
        request.atUid = atUid;
        return generateSocketParams(MessageId.roomChatReq, request);
    }

    //房间用户头像列表
    public static ProtoRequestParams requestRoomUser(long roomId, int page, int count) {
        RoomListUserReq request = new RoomListUserReq();
        request.roomId = roomId;
        request.page = page;
        request.count = count;
        return generateSocketParams(MessageId.roomListUserReq, request);
    }

    //关注
    public static ProtoRequestParams requestFollowUser(long uid) {
        SnsFollowUserReq request = new SnsFollowUserReq();
        request.uid = uid;
        return generateSocketParams(MessageId.snsFollowUserReq, request);
    }

    //取消关注
    public static ProtoRequestParams requestUnFollowUser(long uid) {
        SnsFollowUserReq request = new SnsFollowUserReq();
        request.uid = uid;
        return generateSocketParams(MessageId.snsUnfollowUserReq, request);
    }

    //设置管理员
    public static ProtoRequestParams requestSetAdmin(long roomId, long uid) {
        RoomSetAdminReq request = new RoomSetAdminReq();
        request.roomId = roomId;
        request.uid = uid;
        return generateSocketParams(MessageId.roomSetAdminReq, request);
    }

    //删除管理员
    public static ProtoRequestParams requestRemoveAdmin(long roomId, long uid) {
        RoomSetAdminReq request = new RoomSetAdminReq();
        request.roomId = roomId;
        request.uid = uid;
        request.remove = true;
        return generateSocketParams(MessageId.roomSetAdminReq, request);
    }

    //是否管理员
    public static ProtoRequestParams requestCheckAdmin(long roomId, long uid) {
        RoomCheckAdminReq request = new RoomCheckAdminReq();
        request.roomId = roomId;
        request.uid = uid;
        return generateSocketParams(MessageId.roomCheckAdminReq, request);
    }

    //踢人
    public static ProtoRequestParams requestKickUser(long roomId, long uid) {
        RoomKickUserReq request = new RoomKickUserReq();
        request.roomId = roomId;
        request.kickUid = uid;
        return generateSocketParams(MessageId.roomKickUserReq, request);
    }

    //禁言
    public static ProtoRequestParams requestSilenceUser(long roomId, long uid) {
        RoomSilenceUserReq request = new RoomSilenceUserReq();
        request.roomId = roomId;
        request.silenceUid = uid;
        return generateSocketParams(MessageId.roomSilenceUserReq, request);
    }

    //举报房间
    public static ProtoRequestParams requestReportRoom(long roomId, long uid, int category) {
        RptReportReq request = new RptReportReq();
        request.Type = ReportType.ReportRoom;
        request.Category = category;
        request.RoomId = roomId;
        request.Uid = uid;
        return generateSocketParams(MessageId.rptReportReq, request);
    }

    //举报视频
    public static ProtoRequestParams requestReportVideo(long feedId, long uid, int category) {
        RptReportReq request = new RptReportReq();
        request.Type = ReportType.ReportVideo;
        request.Category = category;
        request.FeedId = feedId;
        request.Uid = uid;
        return generateSocketParams(MessageId.rptReportReq, request);
    }

    //举报图片
    public static ProtoRequestParams requestReportPicture(long feedId, long uid, int category) {
        RptReportReq request = new RptReportReq();
        request.Type = ReportType.ReportPic;
        request.Category = category;
        request.FeedId = feedId;
        request.Uid = uid;
        return generateSocketParams(MessageId.rptReportReq, request);
    }

    //点赞
    public static ProtoRequestParams requestLike(long roomId, boolean first) {
        RoomLikeReq request = new RoomLikeReq();
        request.roomId = roomId;
        request.first = first;
        request.action = 1;
        return generateSocketParams(MessageId.roomLikeReq, request);
    }

    //关注通知
    public static ProtoRequestParams requestLikeFollow(long roomId, boolean first) {
        RoomLikeReq request = new RoomLikeReq();
        request.roomId = roomId;
        request.first = first;
        request.action = 2;
        return generateSocketParams(MessageId.roomLikeReq, request);
    }

    //分享通知
    public static ProtoRequestParams requestLikeShare(long roomId, boolean first) {
        RoomLikeReq request = new RoomLikeReq();
        request.roomId = roomId;
        request.first = first;
        request.action = 3;
        return generateSocketParams(MessageId.roomLikeReq, request);
    }

    //获取管理员列表
    public static ProtoRequestParams requestGetAdminList(long roomId) {
        RoomCommonReq request = new RoomCommonReq();
        request.roomId = roomId;
        return generateSocketParams(MessageId.roomGetAdminListReq, request);
    }

    //获取用户信息
    public static ProtoRequestParams requestUserInfo(long uid) {
        UserInfoCardReq request = new UserInfoCardReq();
        request.uid = uid;
        return generateSocketParams(MessageId.userInfoCardReq, request);
    }

    //观众请求连麦
    public static ProtoRequestParams requestLinkMic(long roomId) {
        RoomCommonReq request = new RoomCommonReq();
        request.roomId = roomId;
        return generateSocketParams(MessageId.roomLinkApplyReq, request);
    }

    //观众取消连麦
    public static ProtoRequestParams requestCancelLinkMic(long roomId) {
        RoomCommonReq request = new RoomCommonReq();
        request.roomId = roomId;
        return generateSocketParams(MessageId.roomLinkCancelApplyReq, request);
    }

    //请求连麦用户列表
    public static ProtoRequestParams requestLinkMicUser(long roomId) {
        RoomCommonReq request = new RoomCommonReq();
        request.roomId = roomId;
        return generateSocketParams(MessageId.roomLinkApplyListReq, request);
    }

    //主播发起连麦邀请
    public static ProtoRequestParams requestLinkMicInvite(long uid) {
        RoomLinkInviteReq request = new RoomLinkInviteReq();
        request.uid = uid;
        return generateSocketParams(MessageId.roomLinkInviteReq, request);
    }

    //观众接受连麦
    private static ProtoRequestParams requestLinkMicConfirm(long roomId, boolean refuse) {
        RoomLinkConfirmReq request = new RoomLinkConfirmReq();
        request.roomId = roomId;
        request.deny = refuse;
        return generateSocketParams(MessageId.roomLinkConfirmReq, request);
    }

    //观众同意连麦
    public static ProtoRequestParams requestAgreeLinkMicConfirm(long roomId) {
        return requestLinkMicConfirm(roomId, false);
    }

    //观众拒绝连麦
    public static ProtoRequestParams requestRefuseLinkMicConfirm(long roomId) {
        return requestLinkMicConfirm(roomId, true);
    }

    //结束连麦
    public static ProtoRequestParams requestStopLinkMic() {
        return generateSocketParams(MessageId.roomLinkStopReq, null);
    }

    //恢复直播
    public static ProtoRequestParams requestResumePush() {
        return generateSocketParams(MessageId.roomContinueLiveReq, null);
    }

    // 手机注册
    public static ProtoRequestParams requestCreatePhone(Integer phoneCountry, Long phone, String verifycode, String password, String imgHead, String nick) {
        AccountCreateReq request = new AccountCreateReq();
        request.phoneCountry = phoneCountry;
        request.phone = phone;
        request.verifycode = verifycode;
        request.secret = MD5Util.getMD5(phone + password);
        request.imgHead = imgHead;
        request.nick = nick;
        request.device = getUserDeviceInfo();
        return generateSocketParams(MessageId.accountCreateReq, request);
    }

    // 登出
    public static ProtoRequestParams requestAccountLogout() {
        AccountLogoutReq request = new AccountLogoutReq();
        return generateSocketParams(MessageId.accountLogoutReq, request);
    }


    // 接收Cocos 的参数来直接跟服务器交互
    public static ProtoRequestParams requestCocosData(String json) {
        JSONObject object = JSONObject.parseObject(json);
        if (object != null && object.containsKey("seq")) {
            object.put("timeout", DEFAULT_TIMEOUT);
            int seqId = object.getIntValue("seq");
            String command = COMMAND_PREFIX_SOCKET + seqId;
            return new ProtoRequestParams(REQUEST_TYPE_SOCKET, command, object.toJSONString());

        }
        return null;
    }

    //大富婆建楼卡
    public static ProtoRequestParams requestRoomHouse() {
        return generateSocketParams(MessageId.roomHouseCardReceiveStatusReq, null);
    }

    /**
     * 1切入前台运行  2切入后台运行
     *
     * @param status
     * @return
     */
    public static ProtoRequestParams requestRunStatus(int status) {
        JSONObject object = new JSONObject();
        object.put("status", status);
        return generateSocketParams(MessageId.runningStatusReq, object);
    }
}
